/**
 * 
 */
package com.crowdgeeks.facebook.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bp.keepcosmos.facebook.Facebook;

@Controller
public class LoginController {

	private static final String apiKey = "1e5f6c81a6d48e17e937d2baf1f655b9";
	private static final String secret = "b0e3afdfd6742337eec1b69f43b8a5f1";
	
	@RequestMapping("/write.do")
	public ModelAndView write(HttpServletRequest request) throws Exception {
		
		ModelAndView mv = new ModelAndView("write");
		return mv;
	}
	
	@RequestMapping("/writeProcess.do")
	public ModelAndView writeProcess(HttpServletRequest request) throws Exception {
		
		ModelAndView mv = new ModelAndView("redirect:/write.do");
		
		String accessToken = request.getParameter("accessToken");
		String feed = request.getParameter("feed");
		
		System.out.println("accessToken : "+accessToken);
		System.out.println("feed : "+feed);
		
		Facebook facebook = new Facebook(apiKey, accessToken);
		
		Map<String, String> data = new HashMap<String, String>();  
		data.put("message", feed);
		data.put("link", "http://www.crowdgeeks.com");  
		data.put("name", "Jay Choi");  
		data.put("picture", "http://www.crowdgeeks.com/img/crowdgeeks_index4.png");   
		
		JSONObject result = facebook.sendPost(data);  
		System.out.println("*** result : "+result);
		String post_id = result.getString("id");  
		//result객체로 결과가 리턴됩니다. (성공하였을 경우 등록된 메시지 id가 돌아옵니다.)
		System.out.println("*** post_id : "+post_id);
		
		JSONObject post_content = facebook.getPost(post_id);  
		System.out.println("*** post_content : "+post_content);
		//feed에 등록한 포스트 데이터를 JSONObject객체로 받아왔습니다.  
		//Album으로 이미지 업로드시에는   
		//data.put("source", image_path); source파라미터에 이미지 경로와 파일명을 넣어줍니다.   
		
		return mv;
	}
	
//	@RequestMapping("/cg/main.do")
//	public ModelAndView main(HttpServletRequest request) throws Exception {
//		
//		ModelAndView mv = new ModelAndView("main");
//		return mv;
//	}
//	
//	@RequestMapping("/index.do")
//	public ModelAndView index(HttpServletRequest request) throws Exception {
//		
//		ModelAndView mv = new ModelAndView("index");
//		return mv;
//	}
	
//    @RequestMapping(value = "/login", method = RequestMethod.GET)
//    public String facebook(@RequestParam(value = "session", required = false) String sessionStr, ModelMap map) throws FacebookException, UnsupportedEncodingException, JSONException {

        // 로그인이 되지 않았다면 로그인을 시킨다. 파라메타로 session을 JSON 형태로 넘겨 받는다.
//    	System.out.println("*** sessionStr : "+ sessionStr);
//        if ("".equals(sessionStr) || null == sessionStr) {
//            //String nextPage = URLEncoder.encode("http://timex.w2dev.net/facebook/", "utf-8");
//            String nextPage = "http://local.cg.com:8080/index2.html";
//            StringBuffer forwardUri = new StringBuffer();
//            forwardUri.append("http://www.facebook.com/login.php?api_key=").append(apiKey)
//                .append("&next=").append(nextPage)
//                .append("&cancel_url=").append("http://local.cg.com:8080/index2.html")
//                .append("&extern=1&fbconnect=1&return_session=1")
//                .append("&req_perms=email");
//            System.out.println(forwardUri.toString());
//            return "redirect:" + forwardUri.toString();
//        }
//        
////		ModelAndView mv = new ModelAndView("login");
//		
//        // 파라메타중 session_key 분리
//        JSONObject json = new JSONObject(sessionStr);
//        String sessionKey = json.getString("session_key");
//
//        IFacebookRestClient<Document> userClient = new FacebookXmlRestClient(apiKey, secret, sessionKey);
//        FacebookJaxbRestClient jaxbClient = new FacebookJaxbRestClient(userClient.getApiKey(), userClient.getSecret(), sessionKey);
//        
//        // 사용자 정보 가져오기.
//        List<Long> users = new ArrayList<Long>();
//        users.add(userClient.users_getLoggedInUser());
//        UsersGetInfoResponse userResponse = jaxbClient.users_getInfo(users, EnumSet.of(ProfileField.UID, ProfileField.NAME, ProfileField.SEX, ProfileField.BIRTHDAY));
//        User user = userResponse.getUser().get(0);
//         
//        map.put("user", user);
////        mv.addObject("user", user);
//        
//        // 친구 정보 가져오기.
//        FriendsGetResponse friendResponse = jaxbClient.friends_get(jaxbClient.getCacheUserId());
//        List<Long> friends = friendResponse.getUid();
//        UsersGetInfoResponse userResponse2 = jaxbClient.users_getInfo(friends, EnumSet.of(ProfileField.UID, ProfileField.NAME, ProfileField.SEX, ProfileField.BIRTHDAY));
//        List<User> friendsInfo = userResponse2.getUser();
//        
//        map.put("friend", friendsInfo);
////        mv.addObject("friend", friendsInfo);
         
//        return "/login";
//	}	
	
}